using System;
using System.IO;
using System.Runtime.Serialization;

namespace pushbomb.composite.core.DynamicObject
{
    public sealed class DynamicObjectSerializationBehavior : DynamicObjectExtension, IDynamicObjectSerializationBehavior
    {
        private DataContractSerializer _serializer;

        public override void Attach(DynamicObject owner)
        {
            if (owner == null) throw new ArgumentNullException("owner");
            DynObject = owner;
            _serializer = new DataContractSerializer(DynObject.GetType());
        
       

        }

        public override void Detach(DynamicObject owner)
        {
            if (owner == null) throw new ArgumentNullException("owner");
            DynObject = null;
            _serializer = null;

        }

        public T Invoke<T>()
        {
            return (T) Invoke();

        }

        public object Invoke()
        {
            if (DynObject == null)
                throw new InvalidOperationException("No instance is attached");

          
            var streamM = new MemoryStream();

          
            _serializer.WriteObject(streamM, DynObject);

            return streamM;



        }
    }
}